package com.heima.controller;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class DelayController implements InitializingBean {

    @Autowired
    RedissonClient redissonClient;

    private ThreadPoolExecutor takeTaskThreadPool = new ThreadPoolExecutor(1,1,0,TimeUnit.SECONDS,new ArrayBlockingQueue<>(10));
    private ThreadPoolExecutor bizThreadPool = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors() * 2,
            120, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(100),
            new ThreadPoolExecutor.CallerRunsPolicy());


    @GetMapping("putTask/{value}/{delaySecond}")
    public String putTask(@PathVariable("value") String value,
                          @PathVariable("delaySecond")Integer delaySecond){
        RBlockingDeque<Object> blockQueue = redissonClient.getBlockingDeque("delay_queue_demo");
        RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockQueue);
        delayedQueue.offer(value, delaySecond, TimeUnit.SECONDS);
        log.info("放入延迟任务, value={}, delay second={}", value, delaySecond);
        return value + "," + delaySecond;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        takeTaskThreadPool.submit(new Runnable() {
            @Override
            public void run() {
                while(true){
                    try {
                        RBlockingDeque<Object> blockQueue = redissonClient.getBlockingDeque("delay_queue_demo");
                        Object value = blockQueue.take();
                        log.info("延迟任务出队，value={}", value);
                        bizThreadPool.submit(new Runnable() {
                            @Override
                            public void run() {
                                // 文章的发布  3
                                //  详情的静态化  2
                            }
                        });
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
    }
}
